package switchviz.gui.component;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.NumberFormat;

import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;


import switchviz.core.ResourceManager;

public class JMaskedTextField extends JPanel implements KeyListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -5253718144040180612L;
	public static final int FLOATNUM = 0;
	public static final int INTNUM = 1;
	private JLabel _label = null;
	private JFormattedTextField _field = null;
	private boolean _checkMin;
	private boolean _checkMax;
	private float _min = 0;
	private float _max = 0;
	private String _keymask = "01234567890";
	
	public JMaskedTextField(String labeltext, int type)
	{
		this(labeltext, type, ResourceManager.getInstance().getConfigurationLabelDimension());
	}
	
	public JMaskedTextField(String labeltext, int type, Dimension dimension)
	{
		_label =  new JLabel(labeltext, JLabel.TRAILING);
		_label.setPreferredSize(dimension);
		
		this.setLayout(new BorderLayout());
		this.add(_label, BorderLayout.WEST);
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setGroupingUsed(false);
		switch(type)
		{
		case FLOATNUM:
			nf.setMinimumFractionDigits(2);
			nf.setMaximumFractionDigits(8);
			_keymask += ",";
			break;
		case INTNUM:
			nf.setMinimumFractionDigits(0);
			nf.setMaximumFractionDigits(0);
			//nf.setParseIntegerOnly(true);
			break;
		}
		
		_field = new JFormattedTextField(nf);
		_field.addKeyListener(this);
		_field.setSize(new Dimension(250, 20));
		
		this.setText("3");
		this.setMaximumSize(new Dimension(800, 20));
		this.add(_field, BorderLayout.CENTER);
	}
	
	public void setAllowNegative()
	{
		_keymask += "-";
	}
	
	public void setMin(float min)
	{
		_min = min;
		_checkMin = true;
	}
	
	public void setMax(float max)
	{
		_max = max;
		_checkMax = true;
	}
	
	public void setText(String text)
	{
		try
		{
			text = String.valueOf(_field.getFormatter().valueToString(Float.valueOf(text)));
		} catch(Exception e) {};
		_field.setText(text);
	}

	public String getText()
	{
		String val = "";
		try
		{
			val = String.valueOf(_field.getFormatter().stringToValue(_field.getText()));
			if(_checkMax && _max < Float.valueOf(val))
				val = String.valueOf(_max);
			if(_checkMin && _min > Float.valueOf(val))
				val = String.valueOf(_min);
			if(val.endsWith(".0"))
				val = val.substring(0, val.length() - 2);
			
		} catch(Exception e) {};
		return val;
	}
	

	public void keyTyped(KeyEvent evt) 
	{
		if(_keymask.indexOf(evt.getKeyChar()) < 0)
			evt.consume();
	}

	public void keyPressed(KeyEvent arg0) {}
	public void keyReleased(KeyEvent arg0) {}
}
